package com.spark.common

import android.app.ProgressDialog
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.NetworkUtils
import com.gyf.barlibrary.ImmersionBar
import com.spark.common.ext.cancel
import com.spark.common.model.NetworkChangeEvent
import io.reactivex.disposables.Disposable
import me.yokeyword.fragmentation.SupportActivity
import me.yokeyword.fragmentation.SupportFragment
import me.yokeyword.fragmentation.anim.DefaultHorizontalAnimator
import me.yokeyword.fragmentation.anim.FragmentAnimator
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * >>>> BaseActivity
 */
abstract class BaseActivity : SupportActivity() {
    /**
     * abstract function
     */
    abstract fun contentResId(): Int

    protected var needImmersion: Boolean = true
    protected var immersionBar: ImmersionBar? = null

    protected var dispose: Disposable? = null
    private var loader: ProgressDialog? = null
    private var networkMonitorReceiver: NetworkMonitorReceiver? = null
    /**
     * 显示加载动画
     */
    fun loading(title: String = "加载中", message: String? = null) {
        loader = ProgressDialog.show(this, title, null, false, false)
    }

    /**
     * 取消加载动画
     */
    fun hideLoader() {
        loader?.cancel()
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(contentResId())
        if (needImmersion) {
            immersionBar = ImmersionBar.with(this)?.apply {
                statusBarDarkFont(true, 0F)
                transparentBar()
                fitsSystemWindows(true)
                init()
            }
        }
        EventBus.getDefault().register(this)

        val iff = IntentFilter()
        iff.addAction("android.net.conn.CONNECTIVITY_CHANGE")
        networkMonitorReceiver = NetworkMonitorReceiver()
        registerReceiver(networkMonitorReceiver, iff)
    }


    override fun onResume() {
        super.onResume()
        // 无网络情况下，系统不会发送网络状况变更的 Intent,需自己手动检查

    }

    /*override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        val fm = supportFragmentManager
        var index = resultCode.shr(16)
        if (index != 0) {
            index--
            if (fm.fragments == null || index < 0) {
                LogUtils.e("Activity result fragment index out of range: 0x$resultCode")
                return
            }
            val fragment = fm.fragments[index]
            if (fragment == null) {
                LogUtils.e("Activity result no fragment exists for index: 0x$resultCode")
            } else {
                handleActivityResult(fragment, requestCode, resultCode, data)
            }
        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    private fun handleActivityResult(fragment: Fragment, requestCode: Int, resultCode: Int, data: Intent?) {
        fragment.onActivityResult(requestCode.and(0xfff), resultCode, data)
        val childs = fragment.childFragmentManager.fragments
        if (childs != null) {
            for (child in childs) {
                handleActivityResult(child, requestCode, resultCode, data)
            }
        }
    }*/

    override fun onDestroy() {
        super.onDestroy()
        dispose.cancel()
        immersionBar?.destroy()
        /*val localView = currentFocus
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        localView?.apply {
            imm.hideSoftInputFromInputMethod(localView.windowToken,2)
        }*/
        KeyboardUtils.hideSoftInput(this)
        EventBus.getDefault().unregister(this)
        unregisterReceiver(networkMonitorReceiver)
    }

    override fun onCreateFragmentAnimator(): FragmentAnimator {
        return DefaultHorizontalAnimator()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNetworkChangedEvent(event: NetworkChangeEvent) {
        LogUtils.e("【ready to do dirty...】")
    }
}

/**
 * >>>> BaseFragment
 */
abstract class BaseFragment : SupportFragment() {
    /**
     * abstract function
     */
    abstract fun contentResId(): Int

    protected var needImmersion: Boolean = true
    protected var immersionBar: ImmersionBar? = null

    protected var dispose: Disposable? = null
    private var loader: ProgressDialog? = null


    /**
     * 显示加载动画
     */
    fun loading(title: String = "加载中", message: String? = null) {
        activity?.apply { loader = ProgressDialog.show(this, title, null, false, false) }
    }

    /**
     * 取消加载动画
     */
    fun hideLoader() {
        loader?.cancel()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(contentResId(), container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (needImmersion) {
            immersionBar = ImmersionBar.with(this)
            immersionBar?.apply {
                keyboardEnable(true)
                navigationBarWithKitkatEnable(false)
                // init()
            }
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            // immersionBar?.init()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        dispose.cancel()
        immersionBar?.destroy()
    }

    override fun onCreateFragmentAnimator(): FragmentAnimator {
        return DefaultHorizontalAnimator()
    }
}

/**
 * <><><><><><><><><><><>  监听网络状态变化
 */
class NetworkMonitorReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        val isConnected = NetworkUtils.isConnected()
        LogUtils.e("【当前网络状态发生变化】isConnected == $isConnected")
        EventBus.getDefault().post(NetworkChangeEvent(isConnected))
    }

}